package com.zhny.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhny.dao.BackendUserDao;
import com.zhny.entity.PageResult;
import com.zhny.pojo.BUser;
import com.zhny.service.BackendUserService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import tk.mybatis.mapper.entity.Example;

import java.util.Map;

@Service
public class BackendUserServiceImpl implements BackendUserService {

    @Autowired //自动注入bean
    private BackendUserDao backendUserDao;

    @Override
    public Page<BUser> pageQuery(Integer currentPage, Integer pageSize, String queryString) {

        PageHelper.startPage(currentPage,pageSize);
        Example example = createExample(queryString);
        return (Page<BUser>)backendUserDao.selectByExample(example);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public BUser findById(Integer id) {
        return  backendUserDao.selectByPrimaryKey(id);
    }

    /**
     * 添加
     * @param bUser
     */
    @Override
    public void add(BUser bUser,String ids) {

       BUser byUsername = backendUserDao.selectByName(bUser.getUsername());

        if (byUsername != null || byUsername.getId()!=bUser.getId()) {
            throw new RuntimeException("登录名重复！！！");
        }


        if (ids != null) {
            String[] roleId = ids.split(",");
            for (int i = 0; i <roleId.length ; i++) {
                bindingUserAndRole(Integer.valueOf(roleId[i]), bUser.getId());
            }
        }

        backendUserDao.insert(bUser);
    }

    /**
     * 用户和角色绑定
     * @param roleId
     * @param id
     */
    private void bindingUserAndRole(Integer roleId, Integer id) {

        backendUserDao.bindingUserAndRole(roleId, id);

    }

    /**
     * 编辑
     * @param bUser
     */
    @Override
    public void edit(BUser bUser,String ids) {


        backendUserDao.updateByPrimaryKey(bUser);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(Integer id) {
        backendUserDao.deleteByPrimaryKey(id);
    }


    /**
     * 构建查询对象
     * @param queryString
     * @return
     */
    private Example createExample(String queryString){
        Example example=new Example(BUser.class);
        Example.Criteria criteria = example.createCriteria();
        if(queryString!=null){
            String[] s = queryString.split("_");
            if (s[0].equals("name")) {
                criteria.andLike("name", "%" + s[1] + "%");
            } else if (s[0].equals("username")) {
                criteria.andLike("username", "%" + s[1] + "%");
            } else if (s[0].equals("email")) {
                criteria.andLike("email", "%" + s[1] + "%");
            }else if (s[0].equals("phone")) {
                criteria.andLike("phone", "%" + s[1] + "%");
            }
        }
        return example;
    }
}
